package com.runfast.waimai.service.impl;

import com.runfast.common.dao.model.*;
import com.runfast.common.exception.BaseException;
import com.runfast.common.security.spring.UserDataDetails;
import com.runfast.common.service.*;
import com.runfast.common.utils.DateUtils;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.mq.AmqpClient;
import com.runfast.pay.Channel;
import com.runfast.pay.RefundType;
import com.runfast.pay.service.PayService;
import com.runfast.waimai.common.Constants;
import com.runfast.waimai.dao.mapper.RunfastGoodsSellRecordMapper;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.entity.Cart;
import com.runfast.waimai.entity.CartItem;
import com.runfast.waimai.entity.CartItemKey;
import com.runfast.waimai.entity.OptionIdPair;
import com.runfast.waimai.service.*;
import com.runfast.waimai.task.async.MessagePushTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.text.RandomStringGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.runfast.waimai.dao.model.RunfastGoodsSellRecord.Status;

@Service
@Slf4j
public class RunfastGoodsSellRecordServiceImpl extends BaseService<RunfastGoodsSellRecord, Integer, RunfastGoodsSellRecordExample> implements RunfastGoodsSellRecordService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RunfastBusinessService businessService;

    @Autowired
    private RunfastCuserService cuserService;

    @Autowired
    private RunfastCuseraddressService cuseraddressService;

    @Autowired
    private RunfastRedPacketRecordService redPacketRecordService;

    @Autowired
    private RunfastActivityService activityService;

    @Autowired
    private RunfastAgentbusinessService agentbusinessService;

    @Autowired
    private RunfastGoodsSellChildrenService goodsSellChildrenService;

    @Autowired
    private RunfastGoodsSellOutStatusService statusService;

    @Autowired
    private RunfastCreditlevelService creditlevelService;

    @Autowired
    private RunfastRefundService refundService;

    @Autowired
    private RunfastBusinessAccountsService businessAccountsService;

    @Autowired
    private RunfastGoodsSellService goodsSellService;

    @Resource(name = "wmPayService")
    private PayService payService;

    @Autowired
    private RunfastMessgeService messgeService;


    @Autowired
    private MessagePushTask messagePushTask;


    @Autowired
    private RunfastOrderActivityService orderActivityService;

    @Autowired
    private RunfastGoodsSellOptionService optionService;

    @Autowired
    private RunfastGoodsSellSubOptionService subOptionService;

    @Autowired
    private CartService cartService;

    @Autowired
    private RunfastGoodsSellOutStatusService goodsSellOutStatusService;

    @Autowired
    private RunfastScrocesetService scrocesetService;

    @Autowired
    private RunfastScorerecordService scorerecordService;

    @Autowired
    private AmqpClient amqpClient;

    @Autowired
    private RunfastAccountrecordService accountrecordService;

    @Autowired
    private RunfastGoodsSellStandardService standardService;

    @Autowired
    private RunfastPrinterService printerService;

    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private RunfastLoginRecordService loginRecordService;

    @Override
    public RunfastGoodsSellRecordMapper getMapper() {
        return (RunfastGoodsSellRecordMapper) super.getMapper();
    }

    @Override
    public Result confirm(Integer businessId, Integer userId, String remark) {
        Validate.notNull(userId, "businessId 不能为null");
        Validate.notNull(userId, "userId 不能为null");

        RunfastBusiness business = businessService.selectByPrimaryKey(businessId);
        Integer agentId = business.getAgentId();
        Boolean bookable = business.getBookable();
        bookable = bookable==null?false:true;

        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentId);
        Date deliveryStart1 = defaultDeliveryTemplate.getStartTimeDay1();
        Date deliveryEnd1 = defaultDeliveryTemplate.getEndTimeDay1();
        Date deliveryStart2 = defaultDeliveryTemplate.getStartTimeNight2();
        Date deliveryEnd2 = defaultDeliveryTemplate.getEndTimeNight2();
        Integer isOpen = businessService.isOpen(businessId,deliveryStart1, deliveryEnd1, deliveryStart2, deliveryEnd2);
        if(isOpen==0&&!bookable) return Result.fail(ResultCode.FAIL, "商家已经休息且不支持预定");
        BigDecimal startPay = business.getStartPay();
        startPay = startPay == null ? BigDecimal.valueOf(0) : startPay;


        RunfastGoodsSellRecord goodsSellRecord = new RunfastGoodsSellRecord();

        //存入登录来源
        RunfastLoginRecordExample loginRecordExample = new RunfastLoginRecordExample();
        loginRecordExample.or().andAccountTypeEqualTo(0).andAccountIdEqualTo(userId).andLogoutTimeIsNull();
        List<RunfastLoginRecord> recordList = loginRecordService.selectByExample(loginRecordExample);
        if(!recordList.isEmpty() && recordList!=null)
            goodsSellRecord.setLoginOn(recordList.get(0).getLoginOn());

        HashOperations hashOperations = redisTemplate.opsForHash();
        Cart cart = (Cart) hashOperations.get(Constants.REDIS_NAMESPACE_PREORDER + userId, businessId);
        if (cart == null) return Result.fail(ResultCode.FAIL, "购物车为空，请添加购物车");

        BigDecimal totalPay = cart.getTotalPay();
        if (totalPay.compareTo(startPay) == -1) return Result.fail(ResultCode.FAIL, "未达到起送价");

        Boolean suportSelf = cart.getUserSuportSelf();
        if (suportSelf == null) return Result.fail(ResultCode.FAIL, "请指定自取还是非自取");
        if (suportSelf) { //自取
            String selfMobile = cart.getSelfMobile();
            Date selfTime = cart.getSelfTime();
            if (StringUtils.isBlank(selfMobile)) return Result.fail(ResultCode.FAIL, "自取手机号不能为空");
            if (selfTime == null) return Result.fail(ResultCode.FAIL, "自取时间不能为空");

            goodsSellRecord.setSelfMobile(selfMobile);
            goodsSellRecord.setSelfTime(selfTime);

        } else { //非自取
            Integer toAddressId = cart.getUserAddressId();
            if (toAddressId == null) return Result.fail(ResultCode.FAIL, "请选择非自取用户地址");
            RunfastCuseraddress cuseraddress = cuseraddressService.selectByPrimaryKey(toAddressId);
            if (cuseraddress == null) return Result.fail(ResultCode.FAIL, "该地址不存在");
            goodsSellRecord.setUserName(cuseraddress.getName());
            goodsSellRecord.setUserMobile(cuseraddress.getMobile());
            goodsSellRecord.setUserPhone(cuseraddress.getPhone());
            goodsSellRecord.setUserAddress(cuseraddress.getUserAddress());
            goodsSellRecord.setAddress(cuseraddress.getAddress());
            goodsSellRecord.setUserAddressLng(cuseraddress.getLongitude());
            goodsSellRecord.setUserAddressLat(cuseraddress.getLatitude());
            goodsSellRecord.setUserAddressId(toAddressId);
            goodsSellRecord.setUserAddressTag(cuseraddress.getTag());
            goodsSellRecord.setUserAddressGender(cuseraddress.getGender());
        }
        goodsSellRecord.setSuportSelf(suportSelf);


        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);


        goodsSellRecord.setBusinessName(business.getName());
        goodsSellRecord.setBusinessId(businessId);
        goodsSellRecord.setBusinessAddr(business.getAddress());
        goodsSellRecord.setBusinessAddressLng(business.getLongitude());
        goodsSellRecord.setBusinessAddressLat(business.getLatitude());
        goodsSellRecord.setBusinessMobile(business.getMobile());
        goodsSellRecord.setUserId(userId);


        Integer distance = cart.getDistance();
        goodsSellRecord.setDistance(distance == null ? null : String.valueOf(distance));
        goodsSellRecord.setGoodsTotal(cart.getTotalNum());

        goodsSellRecord.setIsDeliver(business.getIsDeliver());

        /**
         * 生成随机订单号
         */
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String dateFormated = format.format(new Date());

        String orderNOPrefix = "nw";
        char[][] randomRange = {{'0', '9'}};
        RandomStringGenerator.Builder builder = new RandomStringGenerator.Builder().withinRange(randomRange);
        RandomStringGenerator randomStringGenerator = builder.build();
        String generate = randomStringGenerator.generate(6);
        String orderNo = orderNOPrefix + dateFormated + generate;
        goodsSellRecord.setOrderCode(orderNo);
        goodsSellRecord.setCreateTime(new Date());
        goodsSellRecord.setStatus(Status.created.getCode());
        goodsSellRecord.setStatStr("等待支付");
        goodsSellRecord.setContent(remark);

//        goodsSellRecord.setPrice(BigDecimal.valueOf(cart.getCartDisprice()+cart.getDeliveryFee()+ cart.getTotalPackageFee()));

        goodsSellRecord.setPrice(cart.getCartPrice());

        goodsSellRecord.setPacking(cart.getTotalPackageFee());

        goodsSellRecord.setDeliveryFee(cart.getDeliveryFee());
        goodsSellRecord.setShowps(cart.getFinalDeliveryFee());

        Integer userRedId = cart.getUserRedId();
        goodsSellRecord.setRid(userRedId);

        goodsSellRecord.setTotalpay(totalPay);


        goodsSellRecord.setActivityprice(cart.getOffAmount());

        goodsSellRecord.setAgentId(agentId);
        goodsSellRecord.setDistributionTime(cart.getDeliveryDuration());

        Calendar disTime = Calendar.getInstance();
        disTime.add(Calendar.MINUTE, cart.getDeliveryDuration());
        goodsSellRecord.setDisTime(disTime.getTime());

        goodsSellRecord.setBooked(cart.getBooked());
        goodsSellRecord.setBookTime(cart.getBookTime());

        /**
         * 生成商家当天的订单序列号
         */
        RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();

        Calendar now = Calendar.getInstance();
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);


        goodsSellRecordExample.or().andBusinessIdEqualTo(businessId).andCreateTimeGreaterThan(now.getTime());
        goodsSellRecordExample.setOrderByClause("id desc");
        List<RunfastGoodsSellRecord> goodsSellRecordList = this.selectByExample(goodsSellRecordExample);
        if (goodsSellRecordList.isEmpty()) {

            goodsSellRecord.setOrderNumber(1);
        } else {
            RunfastGoodsSellRecord lastGoodsSellRecord = goodsSellRecordList.get(0);
            goodsSellRecord.setOrderNumber(lastGoodsSellRecord.getOrderNumber() + 1);
        }


        List<RunfastOrderActivity> validActivityList = cart.getValidActivityList();
        /**
         * 代理商总共补贴费用
         */
        BigDecimal totalSubsidy = BigDecimal.valueOf(0);
        RunfastOrderActivity freeDeliveryActivity = null;
        for (RunfastOrderActivity activity : validActivityList) {
            Integer activityType = activity.getActivityType();

            BigDecimal subsidy = activity.getSubsidy() == null ? BigDecimal.valueOf(0) : BigDecimal.valueOf(activity.getSubsidy());

            switch (activityType) {
                case 1:

                    totalSubsidy = totalSubsidy.add(subsidy);

                    break;

                case 2://打折
                case 4://特价
                    break;
                case 5://全免配送费
                case 7://免部分配送费
                    freeDeliveryActivity = activity;
                    totalSubsidy = totalSubsidy.add(subsidy);
                    break;
                case 8://新用户活动
                case 9:
                    totalSubsidy = totalSubsidy.add(subsidy);
                    break;
                case 10://商家红包
                case 11://返红包
                    totalSubsidy = totalSubsidy.add(subsidy);
                    break;

            }


        }


        /**
         * 平台和代理商抽成
         */

        RunfastAgentbusiness leafAgent = agentbusinessService.selectByPrimaryKey(agentId);
        Integer parentAgentId = leafAgent.getAgentId();
        RunfastAgentbusiness parentAgent = null;
        BigDecimal plateformCoefficient = null;
        BigDecimal parentCoefficient = leafAgent.getCoefficient();
        if (parentAgentId != null) {
            parentAgent = agentbusinessService.selectByPrimaryKey(parentAgentId);
            plateformCoefficient = parentAgent.getCoefficient();
            goodsSellRecord.setAcoefficient2(parentAgent.getCoefficient()); //保存的上级代理商抽成系数（？？老版坑爹）
        } else {
            plateformCoefficient = parentCoefficient;
        }
        plateformCoefficient = plateformCoefficient == null ? BigDecimal.valueOf(0) : plateformCoefficient;

        parentCoefficient = parentCoefficient == null ? BigDecimal.valueOf(0) : parentCoefficient;

        BigDecimal leafCoefficient = BigDecimal.valueOf(business.getCoefficient());
        goodsSellRecord.setCoefficient(leafCoefficient);  //商家抽成系数
        goodsSellRecord.setAcoefficient(parentCoefficient); //保存叶子代理商（即没有上级代理商）抽成系数

        BigDecimal baseFee;//参与抽成的费用
        BigDecimal showps = goodsSellRecord.getShowps();//最终的配送费
        Integer drawMode = business.getDrawMode(); //抽成方式

        boolean isDeliver = cart.getIsDeliver() != null && cart.getIsDeliver() == 1;
        if (isDeliver) {//自配送
            goodsSellRecord.setBusinesspay(totalPay.add(totalSubsidy));
            BigDecimal businessDeliveryFee = cart.getFinalDeliveryFee();
            if (freeDeliveryActivity != null) {

                Double less = freeDeliveryActivity.getLess();
                Double subsidy = freeDeliveryActivity.getSubsidy();
                subsidy = subsidy == null ? 0d : subsidy;

                businessDeliveryFee = BigDecimal.valueOf(less).subtract(BigDecimal.valueOf(subsidy)); //商家所得配送费

            }


            //原价的总金额（包含配送费）
            goodsSellRecord.setDisprice(cart.getCartPrice().add(cart.getFinalDeliveryFee()).add(cart.getTotalPackageFee()));

            if (drawMode == null || drawMode == 0) { //折后抽成
                baseFee = totalPay.subtract(businessDeliveryFee);//参与抽成的费用，自配送的配送费不参与抽成
            } else {
                //按照原价抽成
                baseFee = cart.getCartPrice();//参与抽成的费用
            }


        } else {//非自配送

            //商家所得
            goodsSellRecord.setBusinesspay(totalPay.add(totalSubsidy).subtract(showps));

            //原价的总金额（非自配送，商家显示是不包含配送费）
            goodsSellRecord.setDisprice(cart.getCartPrice().add(cart.getTotalPackageFee()));


            if (drawMode == null || drawMode == 0) { //折后抽成
                baseFee = totalPay;//参与抽成的费用，自配送的配送费不参与抽成
            } else {
                //按照原价抽成
                baseFee = cart.getCartPrice();//参与抽成的费用
            }

        }


        //总佣金
        BigDecimal totalIncome = BigDecimal.valueOf(0);

        if (parentAgent != null) {

            if (plateformCoefficient.compareTo(parentCoefficient) == 1) parentCoefficient = plateformCoefficient;
            if (parentCoefficient.compareTo(leafCoefficient) == 1) leafCoefficient = leafCoefficient;

            totalIncome = baseFee.multiply(leafCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);

            BigDecimal plateformIncome = baseFee.multiply(plateformCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            goodsSellRecord.setAgentget(plateformIncome);

            BigDecimal firstIncome = baseFee.multiply(parentCoefficient.subtract(plateformCoefficient)).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            goodsSellRecord.setAgentBusget2(firstIncome);

            BigDecimal secondIncome = baseFee.multiply(leafCoefficient.subtract(parentCoefficient)).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            goodsSellRecord.setAgentBusget(secondIncome.add(totalSubsidy)); //包含补贴

        } else {
            if (plateformCoefficient.compareTo(leafCoefficient) == 1) leafCoefficient = plateformCoefficient;

            totalIncome = baseFee.multiply(leafCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);

            BigDecimal plateformIncome = baseFee.multiply(plateformCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            goodsSellRecord.setAgentget(plateformIncome);


            BigDecimal secondIncome = baseFee.multiply(leafCoefficient.subtract(plateformCoefficient)).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            goodsSellRecord.setAgentBusget(secondIncome.add(totalSubsidy)); //包含补贴


        }

        goodsSellRecord.setBusinessget(totalIncome);


        /**
         * 骑手收入
         */
        RunfastCreditlevelExample creditlevelExample = new RunfastCreditlevelExample();
        creditlevelExample.or().andAgentIdEqualTo(agentId);
        List<RunfastCreditlevel> creditlevelList = creditlevelService.selectByExample(creditlevelExample);

        if (creditlevelList.isEmpty()) throw new BaseException(ResultCode.FAIL, "该代理商没有配置骑手收入模板");

        RunfastCreditlevel creditlevel = creditlevelList.get(0);
        if (DateUtils.nowTimeBetween(creditlevel.getStartTimeDay(), creditlevel.getEndTimeDay())) {

            goodsSellRecord.setShopperMoney(creditlevel.getCommissionDay());
        } else {
            goodsSellRecord.setShopperMoney(creditlevel.getCommissionNight());
        }

        //保存订单
        this.insertSelective(goodsSellRecord);

        /**
         * 保存订单有效的活动
         */


        for (RunfastOrderActivity activity : validActivityList) {
            activity.setOrderId(goodsSellRecord.getId());
            orderActivityService.insert(activity);
        }

        List<CartItem> redisCartItems = cart.getCartItems();

        for (CartItem cartItem : redisCartItems) {
            if (!cartItem.getChecked()) continue;//购物车中未选择的商品直接跳过
            Integer num = cartItem.getNum();

            CartItemKey cartItemKey = cartItem.getKey();
            Integer goodsId = cartItemKey.getGoodsId();
            Integer standarId = cartItemKey.getStandarId();

            RunfastGoodsSellChildren goodsSellChildren = new RunfastGoodsSellChildren();
            goodsSellChildren.setPid(goodsSellRecord.getId());
            goodsSellChildren.setBusinessId(businessId);
            goodsSellChildren.setBusinessName(business.getName());
            goodsSellChildren.setGoodsSellName(cartItem.getGoodsName());
            goodsSellChildren.setGoodsSellId(goodsId);
            goodsSellChildren.setNum(num);
            goodsSellChildren.setPrice(cartItem.getPrice().doubleValue());
            goodsSellChildren.setDisprice(cartItem.getDisprice());
            goodsSellChildren.setTotalDisprice(cartItem.getTotalDisprice() == null ? null : cartItem.getTotalDisprice().doubleValue());
            goodsSellChildren.setTotalprice(cartItem.getTotalPrice().doubleValue());
            goodsSellChildren.setOrderCode(orderNo);
            goodsSellChildren.setGoodsSellStandardId(standarId);
            goodsSellChildren.setGoodsSellStandardName(cartItem.getStandarName());
            goodsSellChildren.setStandarOptionName(cartItem.getStandarOptionName());

            List<OptionIdPair> optionIdPairList = cartItemKey.getOptionIdPairList();
            if (optionIdPairList != null) {
                StringBuilder subOptionBuilder = new StringBuilder();
                for (OptionIdPair optionIdPair : optionIdPairList) {
                    subOptionBuilder.append(optionIdPair.getSubOptionId());
                    subOptionBuilder.append(",");
                }

                if (!optionIdPairList.isEmpty())
                    goodsSellChildren.setOptionIds(subOptionBuilder.substring(0, subOptionBuilder.length() - 1));
            }


            goodsSellChildren.setUserId(userId);
            goodsSellChildren.setStatus(goodsSellRecord.getStatus());
            goodsSellChildren.setCreateTime(new Date());
            goodsSellChildren.setActivityId(cartItem.getActivityId());
            goodsSellChildren.setActivityName(cartItem.getActivityName());
            goodsSellChildren.setActivityType(cartItem.getActivityType());

            /**
             * 保存订单子项
             */
            goodsSellChildrenService.insertSelective(goodsSellChildren);


        }

        /**
         * 保存订单状态
         */
        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();

        goodsSellOutStatus.setBusinessId(businessId);
        goodsSellOutStatus.setBusinessName(business.getName());

        goodsSellOutStatus.setCreateTime(new Date());

        goodsSellOutStatus.setGoodsSellRecordCode(orderNo);
        goodsSellOutStatus.setGoodsSellRecordId(goodsSellRecord.getId());

        goodsSellOutStatus.setOperationId(cuser.getId());
        goodsSellOutStatus.setOperationName(cuser.getMobile());
        goodsSellOutStatus.setSort(Status.created.getCode());
        goodsSellOutStatus.setStatStr("等待支付");
        goodsSellOutStatus.setType(3);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

        statusService.insertSelective(goodsSellOutStatus);


        /**
         * 将用户红包记录状态置为已使用
         */
        if (userRedId != null) {

            RunfastRedPacketRecord redPacketRecord = new RunfastRedPacketRecord();
            redPacketRecord.setId(userRedId);
            redPacketRecord.setUsed(true);

            redPacketRecordService.updateByPrimaryKeySelective(redPacketRecord);
        }

        /**
         * 清除预订单数据
         */
        Long delete = hashOperations.delete(Constants.REDIS_NAMESPACE_PREORDER + userId, businessId);

        /**
         * 清空购物车
         */
        hashOperations.delete(Constants.REDIS_NAMESPACE_CART + userId, businessId);


        /**
         * 发布消息
         *
         */

        amqpClient.publish(AmqpClient.WmBindingKey, goodsSellRecord);


        Map<String, Object> data = new HashMap<>();
        data.put("orderNo", orderNo);
        data.put("orderId", goodsSellRecord.getId());
        data.put("createTime", goodsSellRecord.getCreateTime());
        return Result.ok("", data);
    }


    @Override
    public Result list(Integer userId, Pageable pageable) {

        List<Cart> carList = new ArrayList<>();

        RunfastGoodsSellRecordExample goodsSellRecordExample = new RunfastGoodsSellRecordExample();
        goodsSellRecordExample.or().andUserIdEqualTo(userId);
        goodsSellRecordExample.setOrderByClause("id desc");
        List<RunfastGoodsSellRecord> goodsSellRecordList = this.selectByExampleWithPageable(goodsSellRecordExample, pageable);

        for (RunfastGoodsSellRecord goodsSellRecord : goodsSellRecordList) {
            Cart redisCart = orderDetail(userId, goodsSellRecord);

            if(redisCart!=null)
            carList.add(redisCart);

        }

        return Result.ok("", carList);

    }

    @Override
    public Cart orderDetail(Integer userId, RunfastGoodsSellRecord order) {
        Cart redisCart = new Cart();
        Integer orderId = order.getId();
        Integer toAddressId = order.getUserAddressId();
        Integer businessId = order.getBusinessId();
        RunfastBusiness business = businessService.selectByPrimaryKey(businessId);


        redisCart.setOrderId(orderId);
        redisCart.setUserName(order.getUserName());
        redisCart.setUserMobile(order.getUserMobile());
        redisCart.setUserPhone(order.getUserPhone());
        redisCart.setUserAddress(order.getUserAddress());
        redisCart.setAddress(order.getAddress());
        redisCart.setUserAddressLng(order.getUserAddressLng());
        redisCart.setUserAddressLat(order.getUserAddressLat());
        redisCart.setUserAddressId(toAddressId);
        redisCart.setUserAddressTag(order.getUserAddressTag());
        redisCart.setUserAddressGender(order.getUserAddressGender());


        redisCart.setBusinessId(businessId);

        redisCart.setBusinessImg(business.getImgPath());
        redisCart.setBusinessName(business.getName());
        redisCart.setIsDeliver(business.getIsDeliver());

        redisCart.setBusinessAddr(business.getAddress());
        redisCart.setBusinessAddressLng(business.getLongitude());
        redisCart.setBusinessAddressLat(business.getLatitude());
        redisCart.setBusinessMobile(business.getMobile());
        redisCart.setUserId(userId);

        redisCart.setSuportSelf(business.getSuportSelf());
        redisCart.setUserSuportSelf(order.getSuportSelf());
        redisCart.setSelfMobile(order.getSelfMobile());
        redisCart.setSelfTime(order.getSelfTime());


        redisCart.setDeliveryFee(order.getDeliveryFee());
        redisCart.setFinalDeliveryFee(order.getShowps());
        redisCart.setDeliveryDuration(order.getDistributionTime());
        redisCart.setDisTime(order.getDisTime());
        redisCart.setBooked(order.getBooked());
        redisCart.setBookTime(order.getBookTime());

        redisCart.setTotalPackageFee(order.getPacking());
        redisCart.setCartPrice(order.getPrice());
        redisCart.setOffAmount(order.getActivityprice());
        redisCart.setTotalPay(order.getTotalpay());

        String distance = order.getDistance();
        if (StringUtils.isNotBlank(distance)) {
            redisCart.setDistance(Double.valueOf(distance).intValue());
        }

        redisCart.setTotalNum(order.getGoodsTotal());
        redisCart.setUserRedId(order.getRid());

        RunfastOrderActivityExample orderActivityExample = new RunfastOrderActivityExample();
        orderActivityExample.or().andOrderIdEqualTo(orderId);
        List<RunfastOrderActivity> orderActivityList = orderActivityService.selectByExample(orderActivityExample);

        redisCart.setValidActivityList(orderActivityList);

        redisCart.setOldShopper(order.getOldShopper());
        redisCart.setOldShopperId(order.getOldShopperId());
        redisCart.setOldShopperMobile(order.getOldShopperMobile());

        redisCart.setShopper(order.getShopper());
        redisCart.setShopperId(order.getShopperId());
        redisCart.setShopperMobile(order.getShopperMobile());

        redisCart.setOrderNo(order.getOrderCode());

        redisCart.setCreateTime(order.getCreateTime());
        redisCart.setStatus(order.getStatus());
        redisCart.setStatStr(order.getStatStr());
        redisCart.setRemark(order.getContent());
        redisCart.setCartPrice(order.getPrice());
        redisCart.setIsReceive(order.getIsReceive());
        redisCart.setIsPay(order.getIsPay());
        redisCart.setIsRefund(order.getIsRefund());
        redisCart.setIsCancel(order.getIsCancel());
        redisCart.setIsComent(order.getIsComent());
        redisCart.setRefund(order.getRefund());
        redisCart.setRefundcontext(order.getRefundcontext());

        redisCart.setOffAmount(order.getActivityprice());

        redisCart.setPayTime(order.getPayTime());
        redisCart.setPayType(order.getPayType());
        redisCart.setOrderNumber(order.getOrderNumber());

        List<CartItem> cartItemList = new ArrayList<>();

        RunfastGoodsSellChildrenExample goodsSellChildrenExample = new RunfastGoodsSellChildrenExample();
        goodsSellChildrenExample.or().andPidEqualTo(orderId).andOrderCodeEqualTo(order.getOrderCode());
        List<RunfastGoodsSellChildren> goodsSellChildren = goodsSellChildrenService.selectByExample(goodsSellChildrenExample);

        BigDecimal cartDisprice = BigDecimal.valueOf(0);
        for (RunfastGoodsSellChildren goodsSellChild : goodsSellChildren) {

            Double totalPrice = goodsSellChild.getTotalprice();
            Double totalDisprice = goodsSellChild.getTotalDisprice();

            Integer activityId = goodsSellChild.getActivityId();
            if (activityId != null) {
                cartDisprice = cartDisprice.add(BigDecimal.valueOf(totalDisprice));
            } else {
                cartDisprice = cartDisprice.add(BigDecimal.valueOf(totalPrice));
            }

            CartItem cartItem = new CartItem();
            cartItem.setId(goodsSellChild.getId());

            CartItemKey cartItemKey = new CartItemKey();
            Integer goodsSellId = goodsSellChild.getGoodsSellId();
            cartItemKey.setGoodsId(goodsSellId);
            cartItemKey.setStandarId(goodsSellChild.getGoodsSellStandardId());

            List<OptionIdPair> optionIdPairList = new ArrayList<>();

            String optionIds = goodsSellChild.getOptionIds();
            if (StringUtils.isNotBlank(optionIds)) {
                String[] split = optionIds.split(",");
                for (String s : split) {
                    if (StringUtils.isNotBlank(s)) {
                        Integer subOptionId = Integer.valueOf(s);
                        RunfastGoodsSellSubOption goodsSellSubOption = subOptionService.selectByPrimaryKey(subOptionId);
                        Integer optionId = goodsSellSubOption.getOptionId();
                        OptionIdPair optionIdPair = new OptionIdPair(optionId, subOptionId);

                        optionIdPairList.add(optionIdPair);

                    }

                }
            }
//
            cartItemKey.setOptionIdPairList(optionIdPairList);
            cartItem.setKey(cartItemKey);


            cartItem.setStandarOptionName(goodsSellChild.getStandarOptionName());

            cartItem.setCreateTime(goodsSellChild.getCreateTime());
            cartItem.setNum(goodsSellChild.getNum());
            cartItem.setActivityName(goodsSellChild.getActivityName());
            cartItem.setActivityId(goodsSellChild.getActivityId());
            cartItem.setActivityType(goodsSellChild.getActivityType());

            RunfastGoodsSell goodsSell = goodsSellService.selectByPrimaryKey(goodsSellId);
            if(goodsSell==null) return null;
            cartItem.setGoodsImg(goodsSell.getImgPath());
            cartItem.setStandarName(goodsSellChild.getGoodsSellStandardName());
            cartItem.setGoodsName(goodsSellChild.getGoodsSellName());
            cartItem.setPrice(BigDecimal.valueOf(goodsSellChild.getPrice()));
            cartItem.setDisprice(goodsSellChild.getDisprice());
            cartItem.setTotalPrice(BigDecimal.valueOf(goodsSellChild.getTotalprice()));
            cartItem.setTotalDisprice(goodsSellChild.getTotalDisprice() == null ? null : BigDecimal.valueOf(goodsSellChild.getTotalDisprice()));

            cartItemList.add(cartItem);
        }

        redisCart.setCartDisprice(cartDisprice);
        redisCart.setCartItems(cartItemList);
        return redisCart;
    }


    @Override
    public Result applyCancel(Integer userId, Integer orderId) {

        Validate.notNull(userId, "userId 不能为null");
        Validate.notNull(orderId, "orderId 不能为null");

        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        RunfastGoodsSellRecordExample orderExample = new RunfastGoodsSellRecordExample();
        orderExample.createCriteria().andUserIdEqualTo(userId)
                .andIdEqualTo(orderId);

        List<RunfastGoodsSellRecord> orders = this.selectByExample(orderExample);
        if (orders.isEmpty()) return Result.fail(ResultCode.FAIL, "该用户下不存在该订单");

        RunfastGoodsSellRecord order = orders.get(0);
        Integer status = order.getStatus();
        //订单状态 -1：订单取消  0：客户下单，1：客户已付款 2：商家接单 3：骑手接单 ，4：商家打包 ， 5：商品配送 6：商品送达，7:确认收货 ，8：订单完成

        if (status >= 2 && status < 5) { //用户申请取消订单,商家已接单，需要商家同意才能取消订单
            Integer isCancel = order.getIsCancel();
            if (isCancel != null) {
                switch (isCancel) {
                    case 1:
                        return Result.fail(ResultCode.FAIL, "订单已经申请取消，请等待商家确认");
                    case 2:
                        return Result.fail(ResultCode.FAIL, "商家已同意取消该订单，退款将返还支付账户");
                    case 3:
//                        return Result.fail(ResultCode.FAIL, "商家已拒绝取消该订单");
                        break;
                    case 4:
                        return Result.fail(ResultCode.FAIL, "已同意取消该订单，退款将返还支付账户");
                    default:
                        return Result.fail(ResultCode.FAIL, "未知的取消申请状态");
                }

            }

            RunfastRefund refund = new RunfastRefund();
            refund.setStatus(RunfastRefund.Status.pending.getCode());
            refund.setAmount(order.getTotalpay().multiply(BigDecimal.valueOf(100)).intValue());
            refund.setRefund_no(UUID.randomUUID().toString());
            refund.setOrder_no(order.getOrderCode());
            refund.setOrder_id(order.getId());
            refund.setCreate_time(new Date());
            refund.setDescription("商家已接单，用户申请取消");
            refund.setUpdate_time(new Date());

            refundService.insertSelective(refund);

            /**
             * 更新订单
             */
            RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
            orderUpdate.setId(order.getId());
            orderUpdate.setIsCancel(1);
            orderUpdate.setCancelTime(new Date());

            this.updateByPrimaryKeySelective(orderUpdate);

            /**
             * 保存message
             */
            RunfastMessge messge = new RunfastMessge();
            messge.setTitle("取消订单申请");
            messge.setContent("用户:" + cuser.getMobile() + "申请取消订单:" + order.getOrderCode());
            messge.setCreateTime(new Date());
            messge.setType(2);
            messge.setUserId(order.getBusinessId());
            messge.setUserName(order.getBusinessName());
            messgeService.insertSelective(messge);


            messagePushTask.applyCancelOrderNotify(this.selectByPrimaryKey(orderId));//发生申请取消订单的通知

            return Result.ok("");
        } else if (status == 0) { //用户申请取消订单，订单未付款, 自动取消
            return autoCancel(cuser, order, "订单未付款，自动取消");

        } else if (status == 1) { //用户申请取消订单,订单已付款，商家未接单，自动取消并退款
            return autoCancel(cuser, order, "您的退款已退回您的支付账号，请留意");

        } else if (status == Status.canceled.getCode()) {
            return Result.fail(ResultCode.FAIL, "订单已经取消");
        } else {
            return Result.fail(ResultCode.FAIL, "不能取消当前订单");
        }

    }

    @Override
    public void autoCancel(Integer userId, Integer orderId) {

        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        RunfastGoodsSellRecordExample orderExample = new RunfastGoodsSellRecordExample();
        orderExample.createCriteria().andUserIdEqualTo(userId)
                .andIdEqualTo(orderId);

        List<RunfastGoodsSellRecord> orders = this.selectByExample(orderExample);
        if (!orders.isEmpty()) {

            RunfastGoodsSellRecord order = orders.get(0);
            Integer status = order.getStatus();

            if (status == 0) {
                autoCancel(cuser, order, "支付超时，订单已取消");
            }

            if (status == 1) {
                autoCancel(cuser, order, "商家超时未接单,订单已取消,退款已退回您的支付账户");
            }
        }


    }


    @Override
    public void autoComplete(Integer userId, Integer orderId) {

        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);


        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);

        if (order != null) {


            /**
             * 更新订单状态
             */
            RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
            orderUpdate.setId(orderId);
            orderUpdate.setStatus(Status.completed.getCode());
            orderUpdate.setStatStr("订单超时完成");
            orderUpdate.setReadyTime(new Date());
            this.updateByPrimaryKeySelective(orderUpdate);

            autoComplete(cuser, order);
        }


    }


    @Override
    public Result autoCancel(RunfastCuser cuser, RunfastGoodsSellRecord order, String description) {
        RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
        orderUpdate.setId(order.getId());
        orderUpdate.setStatus(Status.canceled.getCode());
        orderUpdate.setStatStr(description);


        this.updateByPrimaryKeySelective(orderUpdate);


        /**
         * 更新商品信息
         */
        RunfastGoodsSellChildrenExample goodsSellChildrenExample = new RunfastGoodsSellChildrenExample();
        goodsSellChildrenExample.or().andPidEqualTo(order.getId()).andOrderCodeEqualTo(order.getOrderCode());
        List<RunfastGoodsSellChildren> goodsSellChildren = goodsSellChildrenService.selectByExample(goodsSellChildrenExample);

        Map<Integer, Integer> goodsSalesNumMap = new HashMap<>();
        for (RunfastGoodsSellChildren goodsSellChild : goodsSellChildren) {


            /**
             * 更新商品库存
             */

            Integer standarId = goodsSellChild.getGoodsSellStandardId();
            Integer num = goodsSellChild.getNum();
            standardService.updateStock(goodsSellChild.getGoodsSellId(), standarId, num);

        }


//        Integer status = order.getStatus(); //支付状态
        Integer isPay = order.getIsPay(); //是否已经支付
        if (isPay != null && isPay == 1) { //用户已经支付，
            RunfastRefund refund = new RunfastRefund();
            refund.setStatus(RunfastRefund.Status.pending.getCode());
            refund.setAmount(order.getTotalpay().multiply(BigDecimal.valueOf(100)).intValue());
            refund.setRefund_no(UUID.randomUUID().toString());
            refund.setOrder_no(order.getOrderCode());
            refund.setOrder_id(order.getId());
            refund.setCreate_time(new Date());
            refund.setDescription(description);
            refund.setUpdate_time(new Date());

            refundService.insertSelective(refund);
            PayServiceImpl payService = (PayServiceImpl) this.payService;

            Result result = payService.refund(refund);

//                    Result result = this.payService.refund(order.getOrderCode(), UUID.randomUUID().toString(), order.getTotalpay().multiply(BigDecimal.valueOf(100)).intValue(), "商户未接单，自动退款");
            if (result.isSuccess()) {
                //订单状态操作记录
                RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                goodsSellOutStatus.setBusinessId(order.getBusinessId());
                goodsSellOutStatus.setBusinessName(order.getBusinessName());
                goodsSellOutStatus.setCreateTime(new Date());
                goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
                goodsSellOutStatus.setGoodsSellRecordId(order.getId());
                goodsSellOutStatus.setOperationId(cuser.getId());
                goodsSellOutStatus.setOperationName(cuser.getMobile());
                goodsSellOutStatus.setSort(-1);
                goodsSellOutStatus.setStatStr(description);
                goodsSellOutStatus.setType(3);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

                goodsSellOutStatusService.insertSelective(goodsSellOutStatus);

                /**
                 * 发送消息
                 *
                 */
                amqpClient.publish(AmqpClient.WmBindingKey, this.selectByPrimaryKey(order.getId()));


                return Result.ok("取消订单成功，支付金额稍后将原路返还");
            } else {
                throw new BaseException(ResultCode.FAIL, "取消订单失败,原因：" + result.getErrorMsg());//抛出异常，回滚事务
            }
        } else {
            //订单状态操作记录
            RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
            goodsSellOutStatus.setBusinessId(order.getBusinessId());
            goodsSellOutStatus.setBusinessName(order.getBusinessName());
            goodsSellOutStatus.setCreateTime(new Date());
            goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
            goodsSellOutStatus.setGoodsSellRecordId(order.getId());
            goodsSellOutStatus.setOperationId(cuser.getId());
            goodsSellOutStatus.setOperationName(cuser.getMobile());
            goodsSellOutStatus.setSort(-1);
            goodsSellOutStatus.setStatStr(description);
            goodsSellOutStatus.setType(3);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

            goodsSellOutStatusService.insertSelective(goodsSellOutStatus);

            /**
             * 发送消息
             *
             */
            amqpClient.publish(AmqpClient.WmBindingKey, this.selectByPrimaryKey(order.getId()));

            return Result.ok("取消订单成功");
        }
    }


    public Result autoComplete(RunfastCuser cuser, RunfastGoodsSellRecord order) {


        /**
         * 更新商家信息
         */
        RunfastBusiness business = businessService.selectByPrimaryKey(order.getBusinessId());
        Integer salesnum = business.getSalesnum() == null ? 0 : business.getSalesnum();

        RunfastBusiness runfastBusiness = new RunfastBusiness();
        runfastBusiness.setId(business.getId());
        runfastBusiness.setSalesnum(salesnum + order.getGoodsTotal());

        businessService.updateByPrimaryKeySelective(runfastBusiness);

        /**
         * 更新商品信息
         */
        RunfastGoodsSellChildrenExample goodsSellChildrenExample = new RunfastGoodsSellChildrenExample();
        goodsSellChildrenExample.or().andPidEqualTo(order.getId()).andOrderCodeEqualTo(order.getOrderCode());
        List<RunfastGoodsSellChildren> goodsSellChildren = goodsSellChildrenService.selectByExample(goodsSellChildrenExample);

        Map<Integer, Integer> goodsSalesNumMap = new HashMap<>();
        for (RunfastGoodsSellChildren goodsSellChild : goodsSellChildren) {


            /**
             * 更新规格销量
             */

            Integer standarId = goodsSellChild.getGoodsSellStandardId();
            Integer num = goodsSellChild.getNum();
            RunfastGoodsSellStandard standard = standardService.selectByPrimaryKey(standarId);


            Integer standardSaleNum = standard.getSale_num();
            standardSaleNum = standardSaleNum == null ? 0 : standardSaleNum;


            RunfastGoodsSellStandard standardUpdate = new RunfastGoodsSellStandard();
            standardUpdate.setId(standarId);
            standardUpdate.setSale_num(standardSaleNum + num);

            standardService.updateByPrimaryKeySelective(standardUpdate);


            Integer goodsId = goodsSellChild.getGoodsSellId();

            Integer prenum = goodsSalesNumMap.get(goodsId);
            if (prenum == null) goodsSalesNumMap.put(goodsId, num);
            else goodsSalesNumMap.put(goodsId, prenum + num);


        }

        for (Map.Entry<Integer, Integer> entry : goodsSalesNumMap.entrySet()) {
            Integer goodsId = entry.getKey();
            Integer num = entry.getValue();

            RunfastGoodsSell goodsSell = new RunfastGoodsSell();
            goodsSell.setId(goodsId);
            Integer goodsSellNum = goodsSell.getNum();
            goodsSellNum = goodsSellNum == null ? 0 : goodsSellNum;
            goodsSell.setSalesnum(goodsSellNum + num);

            goodsSellService.updateByPrimaryKeySelective(goodsSell);

        }


        /**
         * 保存积分记录
         */
        RunfastScorerecord scorerecord = new RunfastScorerecord();
        scorerecord.setCardnumber(order.getOrderCode());
        scorerecord.setCid(cuser.getId());
        scorerecord.setCreateTime(new Date());
        scorerecord.setMobile(cuser.getMobile());
        scorerecord.setMonetary(order.getTotalpay());
        scorerecord.setName(cuser.getName());
        scorerecord.setType(2);

        List<RunfastScroceset> scrocesetList = scrocesetService.selectByExample(null);
        if (scrocesetList.isEmpty()) {
            scorerecord.setScore(order.getTotalpay().intValue());
        } else {
            RunfastScroceset scroceset = scrocesetList.get(0);
            scorerecord.setScore(order.getTotalpay().multiply(BigDecimal.valueOf(scroceset.getConsumexs())).intValue());
        }

        scorerecordService.insertSelective(scorerecord);


        /**
         * 更新用户信息
         */
        RunfastCuser runfastCuser = new RunfastCuser();
        runfastCuser.setId(cuser.getId());

        Double score = cuser.getScore();
        score = score == null ? 0d : score;
        runfastCuser.setScore(score + scorerecord.getScore());

        cuserService.updateByPrimaryKeySelective(runfastCuser);


        //订单状态操作记录
        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
        goodsSellOutStatus.setBusinessId(order.getBusinessId());
        goodsSellOutStatus.setBusinessName(order.getBusinessName());
        goodsSellOutStatus.setCreateTime(new Date());
        goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
        goodsSellOutStatus.setGoodsSellRecordId(order.getId());
        goodsSellOutStatus.setOperationId(-1);
        goodsSellOutStatus.setOperationName("系统");
        goodsSellOutStatus.setSort(8);
        goodsSellOutStatus.setStatStr("已接订单超时未完成，系统自动完成");
        goodsSellOutStatus.setType(1);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

        goodsSellOutStatusService.insertSelective(goodsSellOutStatus);


        /**
         * 发送消息
         *
         */
        amqpClient.publish(AmqpClient.WmBindingKey, this.selectByPrimaryKey(order.getId()));

        return Result.ok("取消订单成功");
    }

    @Deprecated
    @Override
    public Result applyRefund(Integer orderId, String reason, RefundType refundType, Integer refundAmount) {
        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);
        if (order == null) return Result.fail(ResultCode.FAIL, "该订单不存在");
        //订单状态编码-3:商家拒单-1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
        Integer status = order.getStatus();
        if (status == 8) {
//            RunfastRefundExample refundExample = new RunfastRefundExample();
//            refundExample.or().andOrder_idEqualTo(orderId);
//            List<RunfastRefund> refundList = refundService.selectByExample(refundExample);
//            if (!refundList.isEmpty()) return Result.fail(ResultCode.FAIL, "已经有一笔退款申请，请等待商家确认");

            Integer isRefund = order.getIsRefund();


            if (isRefund == 1) return Result.fail(ResultCode.FAIL, "已经有一笔退款申请，请等待商家确认");
            if (isRefund == 2 || isRefund == 3) return Result.fail(ResultCode.FAIL, "订单已被商家处理");

            Date createTime = order.getCreateTime();
            if (createTime != null) {
                Calendar completeTime = Calendar.getInstance();
                completeTime.setTime(createTime);
                completeTime.add(Calendar.HOUR_OF_DAY, 2);
                Calendar now = Calendar.getInstance();
                if (!now.before(completeTime)) return Result.fail(ResultCode.FAIL, "只能在订单创建后的24小时内申请退款");
            }


            BigDecimal totalpay = order.getTotalpay();

            //抛弃，需求不明确
//            int compareTo = totalpay.subtract(refund).compareTo(BigDecimal.valueOf(refundAmount)); //是否还可以退，例如之前退了部分，剩余还可以退
//            if(isRefund==1&&compareTo==-1)return Result.fail(ResultCode.FAIL, "退款金额不能超过剩余可退金额");

            switch (refundType) {
                case full_with_fee:
                    refundAmount = totalpay.multiply(BigDecimal.valueOf(100)).intValue();
                    break;
                case full_without_fee:
                    refundAmount = totalpay.subtract(order.getShowps()).multiply(BigDecimal.valueOf(100)).intValue();
                    break;
                case part:

                    if (refundAmount == null) return Result.fail(ResultCode.FAIL, "部分退款需指定退款金额");
                    if (refundAmount > totalpay.multiply(BigDecimal.valueOf(100)).intValue())
                        return Result.fail(ResultCode.FAIL, "退款金额不能超过支付金额");

                    break;
                default:
                    return Result.fail(ResultCode.FAIL, "不支持该refundType");
            }

            RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
            orderUpdate.setId(orderId);
            orderUpdate.setIsRefund(1);
            orderUpdate.setRefundType(refundType.ordinal());


            RunfastRefund refund = new RunfastRefund();
            refund.setOrder_id(orderId);
            refund.setOrder_no(order.getOrderCode());
            refund.setCreate_time(new Date());
            refund.setAmount(refundAmount);
            refund.setUpdate_time(new Date());
            refund.setDescription(reason);
            refund.setStatus(RunfastRefund.Status.create.getCode());


            refundService.insert(refund);//保存退款申请


            messagePushTask.applyRefundNotify(this.selectByPrimaryKey(orderId));
        } else {
            return Result.fail(ResultCode.FAIL, "只有完成的订单才能申请退款");
        }


        return Result.ok("");
    }

    @Override
    public Result applyRefund(Integer orderId, List<Integer> orderItemId, String reason) {


        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);
        if (order == null) return Result.fail(ResultCode.FAIL, "该订单不存在");


        //订单状态编码-3:商家拒单-1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
        Integer status = order.getStatus();
        if (status != 8) return Result.fail(ResultCode.FAIL, "只有完成的订单才能申请退款");

        Integer isRefund = order.getIsRefund();

        if (isRefund != null) {

            switch (isRefund) {
                case 1:
                    return Result.fail(ResultCode.FAIL, "订单已经申请退款，请等待商家确认");
                case 2:
                    return Result.fail(ResultCode.FAIL, "商家已同意退款，退款将返还支付账户");
                case 3:
                    return Result.fail(ResultCode.FAIL, "商家已拒绝退款");
                case 4:
                    return Result.fail(ResultCode.FAIL, "已同意退款，退款将返还支付账户");
                default:
                    return Result.fail(ResultCode.FAIL, "未知的退款申请状态");
            }
        }

        Date create = order.getCreateTime();
        if (create != null) {
            Calendar createTime = Calendar.getInstance();
            createTime.setTime(create);
            createTime.add(Calendar.DAY_OF_MONTH, 1);
            Calendar now = Calendar.getInstance();
            if (!now.before(createTime)) return Result.fail(ResultCode.FAIL, "只能在订单创建后的24小时内申请退款");
        }

        BigDecimal totalpay = order.getTotalpay();

        //抛弃，需求不明确
//            int compareTo = totalpay.subtract(refund).compareTo(BigDecimal.valueOf(refundAmount)); //是否还可以退，例如之前退了部分，剩余还可以退
//            if(isRefund==1&&compareTo==-1)return Result.fail(ResultCode.FAIL, "退款金额不能超过剩余可退金额");

        RunfastGoodsSellChildrenExample checkedChildrenExample = new RunfastGoodsSellChildrenExample();
        checkedChildrenExample.or().andOrderCodeEqualTo(order.getOrderCode()).andIdIn(orderItemId);
        List<RunfastGoodsSellChildren> checkedChildren = goodsSellChildrenService.selectByExample(checkedChildrenExample);

        if (checkedChildren.size() != orderItemId.size()) return Result.fail(ResultCode.FAIL, "存在非法的orderItemId");

        RunfastGoodsSellChildrenExample allChildrenExample = new RunfastGoodsSellChildrenExample();
        allChildrenExample.or().andOrderCodeEqualTo(order.getOrderCode());

        List<RunfastGoodsSellChildren> allChildren = goodsSellChildrenService.selectByExample(allChildrenExample);

        BigDecimal cartDisprice = BigDecimal.valueOf(0);
        for (RunfastGoodsSellChildren allChild : allChildren) {
            Double totalPrice = allChild.getTotalprice();
            Double totalDisprice = allChild.getTotalDisprice();

            Integer activityId = allChild.getActivityId();
            if (activityId != null) {
                cartDisprice = cartDisprice.add(BigDecimal.valueOf(totalDisprice));
            } else {
                cartDisprice = cartDisprice.add(BigDecimal.valueOf(totalPrice));
            }
        }


        BigDecimal refundAmount = BigDecimal.valueOf(0);
        if (checkedChildren.size() == allChildren.size()) { //全选
            refundAmount = totalpay;

        } else { //选择部分

            /**
             * 计算退款百分比
             */
            BigDecimal dispriceRefundAmount = BigDecimal.valueOf(0);

            for (RunfastGoodsSellChildren child : checkedChildren) {
                Double totalPrice = child.getTotalprice();
                Double totalDisprice = child.getTotalDisprice();

                Integer activityId = child.getActivityId();
                if (activityId != null) {
                    dispriceRefundAmount = dispriceRefundAmount.add(BigDecimal.valueOf(totalDisprice));
                } else {
                    dispriceRefundAmount = dispriceRefundAmount.add(BigDecimal.valueOf(totalPrice));

                }

            }

            refundAmount = dispriceRefundAmount.multiply(totalpay.subtract(order.getShowps())).divide(cartDisprice, 2, RoundingMode.HALF_UP);

        }

        RefundType refundType = allChildren.size() == checkedChildren.size() ? RefundType.full_with_fee : RefundType.part;

        Integer amount = null;
        switch (refundType) {
            case full_with_fee:
                amount = totalpay.multiply(BigDecimal.valueOf(100)).intValue();
                break;
                /*case full_without_fee:
                    refundAmount = totalpay.subtract(order.getShowps()).multiply(BigDecimal.valueOf(100)).intValue();
                    break;*/
            case part:

                amount = refundAmount.multiply(BigDecimal.valueOf(100)).intValue();

                break;
            default:
                return Result.fail(ResultCode.FAIL, "不支持该refundType");
        }

        RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
        orderUpdate.setId(orderId);
        orderUpdate.setIsRefund(1);
        orderUpdate.setRefundType(refundType.ordinal());

        this.updateByPrimaryKeySelective(orderUpdate);


        RunfastRefund refund = new RunfastRefund();
        refund.setOrder_id(orderId);
        refund.setOrder_no(order.getOrderCode());
        refund.setCreate_time(new Date());
        refund.setAmount(amount);
        refund.setUpdate_time(new Date());
        refund.setDescription(reason);
        refund.setStatus(RunfastRefund.Status.create.getCode());


        refundService.insert(refund);//保存退款申请

        messagePushTask.applyRefundNotify(this.selectByPrimaryKey(orderId));
        return Result.ok("商家将在120分钟内处理您的退款申请");
    }

    @Override
    public List<Map<String, Integer>> findCancelNewOrder(Date time) {
        return getMapper().findCancelNewOrder(time);
    }

    @Override
    public List<Map<String, Integer>> findCancelPaidOrder(Date time) {
        return getMapper().findCancelPaidOrder(time);
    }

    @Override
    public Integer resetIsComent(int orderId) {
        return getMapper().resetIsComent(orderId);
    }

    @Override
    public Result applyRefundInfo(Integer orderId, List orderItemId) {
        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);
        if (order == null) return Result.fail(ResultCode.FAIL, "该订单不存在");


        //订单状态编码-3:商家拒单-1：订单取消  0：客户下单，1：客户已付款  2：商家接单  3：骑手接单   4：商品打包 ，5：商品配送 6：商品送达，7:确认收货 ，8：订单完成
        Integer status = order.getStatus();

        if (status != 8) return Result.fail(ResultCode.FAIL, "只有完成的订单才能申请退款");

        Integer isRefund = order.getIsRefund();

        if (isRefund != null) {
            if (isRefund == 1) return Result.fail(ResultCode.FAIL, "已经有一笔退款申请，请等待商家确认");
            if (isRefund == 2 || isRefund == 3) return Result.fail(ResultCode.FAIL, "订单已被商家处理");
        }


        BigDecimal totalpay = order.getTotalpay();

        //抛弃，需求不明确
//            int compareTo = totalpay.subtract(refund).compareTo(BigDecimal.valueOf(refundAmount)); //是否还可以退，例如之前退了部分，剩余还可以退
//            if(isRefund==1&&compareTo==-1)return Result.fail(ResultCode.FAIL, "退款金额不能超过剩余可退金额");

        RunfastGoodsSellChildrenExample checkedChildrenExample = new RunfastGoodsSellChildrenExample();
        checkedChildrenExample.or().andOrderCodeEqualTo(order.getOrderCode()).andIdIn(orderItemId);
        List<RunfastGoodsSellChildren> checkedChildren = goodsSellChildrenService.selectByExample(checkedChildrenExample);

        if (checkedChildren.size() != orderItemId.size()) return Result.fail(ResultCode.FAIL, "存在非法的orderItemId");

        RunfastGoodsSellChildrenExample allChildrenExample = new RunfastGoodsSellChildrenExample();
        allChildrenExample.or().andOrderCodeEqualTo(order.getOrderCode());

        List<RunfastGoodsSellChildren> allChildren = goodsSellChildrenService.selectByExample(allChildrenExample);

        BigDecimal cartDisprice = BigDecimal.valueOf(0);
        for (RunfastGoodsSellChildren allChild : allChildren) {
            Double totalPrice = allChild.getTotalprice();
            Double totalDisprice = allChild.getTotalDisprice();

            Integer activityId = allChild.getActivityId();
            if (activityId != null) {
                cartDisprice = cartDisprice.add(BigDecimal.valueOf(totalDisprice));
            } else {
                cartDisprice = cartDisprice.add(BigDecimal.valueOf(totalPrice));
            }

        }


        BigDecimal refundAmount = BigDecimal.valueOf(0);
        if (checkedChildren.size() == allChildren.size()) { //全选
            refundAmount = totalpay;

        } else { //选择部分

            /**
             * 计算退款百分比
             */
            BigDecimal dispriceRefundAmount = BigDecimal.valueOf(0);

            for (RunfastGoodsSellChildren child : checkedChildren) {
                Double totalPrice = child.getTotalprice();
                Double totalDisprice = child.getTotalDisprice();

                Integer activityId = child.getActivityId();
                if (activityId != null) {
                    dispriceRefundAmount = dispriceRefundAmount.add(BigDecimal.valueOf(totalDisprice));
                } else {
                    dispriceRefundAmount = dispriceRefundAmount.add(BigDecimal.valueOf(totalPrice));

                }

            }

            refundAmount = dispriceRefundAmount.multiply(totalpay.subtract(order.getShowps())).divide(cartDisprice, 2, RoundingMode.HALF_UP);

        }


        return Result.ok("", refundAmount);
    }


    @Override
    public Map<String, Object> findLastestOrder(Integer agentId, Integer userId) {
        return getMapper().findLastestOrder(agentId, userId);
    }


    @Override
    public List<Map<String, Integer>> findCompletableOrder(Date time) {
        return getMapper().findCompletableOrder(time);
    }

    @Override
    public List<Map<String, Integer>> findConfirmRefundOrder(Date time) {
        return getMapper().findConfirmRefundOrder(time);
    }

    @Override
    public List<Map<String, Integer>> findConfirmCancelOrder(Date time) {
        return getMapper().findConfirmCancelOrder(time);
    }

    @Override
    public void confirmCancel(Integer userId, Integer orderId) {
        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        RunfastGoodsSellRecordExample orderExample = new RunfastGoodsSellRecordExample();
        orderExample.createCriteria().andUserIdEqualTo(userId)
                .andIdEqualTo(orderId);

        List<RunfastGoodsSellRecord> orders = this.selectByExample(orderExample);
        if (!orders.isEmpty()) {

            RunfastGoodsSellRecord order = orders.get(0);

            RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
            orderUpdate.setId(order.getId());
            orderUpdate.setIsCancel(4);
            orderUpdate.setStatus(Status.canceled.getCode());
            orderUpdate.setStatStr("用户申请取消，商家超时未处理，系统自动取消");

            this.updateByPrimaryKeySelective(orderUpdate);

            /**
             * 更新商品信息
             */
            RunfastGoodsSellChildrenExample goodsSellChildrenExample = new RunfastGoodsSellChildrenExample();
            goodsSellChildrenExample.or().andPidEqualTo(order.getId()).andOrderCodeEqualTo(order.getOrderCode());
            List<RunfastGoodsSellChildren> goodsSellChildren = goodsSellChildrenService.selectByExample(goodsSellChildrenExample);

            Map<Integer, Integer> goodsSalesNumMap = new HashMap<>();
            for (RunfastGoodsSellChildren goodsSellChild : goodsSellChildren) {


                /**
                 * 更新商品库存和销量
                 */

                Integer standarId = goodsSellChild.getGoodsSellStandardId();
                Integer num = goodsSellChild.getNum();
                standardService.updateStock(goodsSellChild.getGoodsSellId(), standarId, -num);

            }

            Integer isPay = order.getIsPay(); //是否已经支付
            if (isPay != null && isPay == 1) { //用户已经支付，
                RunfastRefundExample refundExample = new RunfastRefundExample();
                refundExample.or().andOrder_idEqualTo(orderId);
                List<RunfastRefund> refundList = refundService.selectByExample(refundExample);
                RunfastRefund refund = refundList.get(0);
                PayServiceImpl payService = (PayServiceImpl) this.payService;

                Result result = payService.refund(refund);

//                    Result result = this.payService.refund(order.getOrderCode(), UUID.randomUUID().toString(), order.getTotalpay().multiply(BigDecimal.valueOf(100)).intValue(), "商户未接单，自动退款");
                if (result.isSuccess()) {
                    //订单状态操作记录
                    RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                    goodsSellOutStatus.setBusinessId(order.getBusinessId());
                    goodsSellOutStatus.setBusinessName(order.getBusinessName());
                    goodsSellOutStatus.setCreateTime(new Date());
                    goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
                    goodsSellOutStatus.setGoodsSellRecordId(order.getId());
                    goodsSellOutStatus.setOperationId(cuser.getId());
                    goodsSellOutStatus.setOperationName(cuser.getMobile());
                    goodsSellOutStatus.setSort(-1);
                    goodsSellOutStatus.setStatStr("用户申请取消，商家超时未处理，系统自动取消");
                    goodsSellOutStatus.setType(3);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

                    goodsSellOutStatusService.insertSelective(goodsSellOutStatus);

                    /**
                     * 发送消息
                     *
                     */
                    amqpClient.publish(AmqpClient.WmBindingKey, this.selectByPrimaryKey(order.getId()));


                } else {
                    throw new BaseException(ResultCode.FAIL, "取消订单失败,原因：" + result.getErrorMsg());//抛出异常，回滚事务
                }
            }
        }
    }

    @Override
    public void confirmRefund(Integer userId, Integer orderId) {
        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);


        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);


        Integer isRefund = order.getIsRefund();
        if (isRefund != null && isRefund == 1) {
            RunfastRefundExample refundExample = new RunfastRefundExample();
            refundExample.or().andOrder_idEqualTo(orderId);
            List<RunfastRefund> refundList = refundService.selectByExample(refundExample);
            RunfastRefund refund = refundList.get(0);
            BigDecimal amountRefund = BigDecimal.valueOf(refund.getAmount()).divide(BigDecimal.valueOf(100), 2);
            PayServiceImpl payService = (PayServiceImpl) this.payService;

            Result result = payService.refund(refund);

            if (result.isSuccess()) {

                RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
                orderUpdate.setId(order.getId());
                orderUpdate.setRefund(amountRefund);
                orderUpdate.setIsRefund(4);
                /**
                 * 更新抽成
                 */
                RunfastBusiness business = businessService.selectByPrimaryKey(order.getBusinessId());
                order.setTotalpay(order.getTotalpay().subtract(amountRefund));
                populateIncome(order, orderUpdate, business);

                this.updateByPrimaryKeySelective(orderUpdate);

                //订单状态操作记录
                RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
                goodsSellOutStatus.setBusinessId(order.getBusinessId());
                goodsSellOutStatus.setBusinessName(order.getBusinessName());
                goodsSellOutStatus.setCreateTime(new Date());
                goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
                goodsSellOutStatus.setGoodsSellRecordId(order.getId());
                goodsSellOutStatus.setOperationId(cuser.getId());
                goodsSellOutStatus.setOperationName(cuser.getMobile());
                goodsSellOutStatus.setSort(-1);
                goodsSellOutStatus.setStatStr("用户申请退款，商家超时未处理，系统自动退款");
                goodsSellOutStatus.setType(3);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

                goodsSellOutStatusService.insertSelective(goodsSellOutStatus);

                /**
                 * 发送消息
                 *
                 */
                amqpClient.publish(AmqpClient.WmBindingKey, this.selectByPrimaryKey(order.getId()));


            } else {
                throw new BaseException(ResultCode.FAIL, "取消订单失败,原因：" + result.getErrorMsg());//抛出异常，回滚事务
            }
        }
    }

    /**
     * 计算抽成
     *
     * @param order
     * @param orderUpdate
     * @param business
     */
    private void populateIncome(RunfastGoodsSellRecord order, RunfastGoodsSellRecord orderUpdate, RunfastBusiness business) {
        Integer orderId = order.getId();


        /**
         * 平台和代理商抽成
         */
        Integer agentId = business.getAgentId();
        RunfastAgentbusiness leafAgent = agentbusinessService.selectByPrimaryKey(agentId);
        Integer parentAgentId = leafAgent.getAgentId();
        RunfastAgentbusiness parentAgent = null;
        BigDecimal plateformCoefficient = null;
        BigDecimal parentCoefficient = leafAgent.getCoefficient();
        if (parentAgentId != null) {
            parentAgent = agentbusinessService.selectByPrimaryKey(parentAgentId);
            plateformCoefficient = parentAgent.getCoefficient();
            orderUpdate.setAcoefficient2(parentAgent.getCoefficient()); //保存的上级代理商抽成系数（？？老版坑爹）
        } else {
            plateformCoefficient = parentCoefficient;
        }
        plateformCoefficient = plateformCoefficient == null ? BigDecimal.valueOf(0) : plateformCoefficient;

        parentCoefficient = parentCoefficient == null ? BigDecimal.valueOf(0) : parentCoefficient;

        BigDecimal leafCoefficient = BigDecimal.valueOf(business.getCoefficient());
        orderUpdate.setCoefficient(leafCoefficient);  //商家抽成系数
        orderUpdate.setAcoefficient(parentCoefficient); //保存叶子代理商（即没有上级代理商）抽成系数
        BigDecimal baseFee;//参与抽成的费用
        /**
         * 代理商总共补贴费用
         */
        BigDecimal totalSubsidy = BigDecimal.valueOf(0);
        RunfastOrderActivity freeDeliveryActivity = null;

        RunfastOrderActivityExample orderActivityExample = new RunfastOrderActivityExample();
        orderActivityExample.or().andOrderIdEqualTo(orderId);
        List<RunfastOrderActivity> validActivityList = orderActivityService.selectByExample(orderActivityExample);
        for (RunfastOrderActivity activity : validActivityList) {
            Integer activityType = activity.getActivityType();

            BigDecimal subsidy = activity.getSubsidy() == null ? BigDecimal.valueOf(0) : BigDecimal.valueOf(activity.getSubsidy());

            switch (activityType) {
                case 1:

                    totalSubsidy = totalSubsidy.add(subsidy);

                    break;

                case 2://打折
                case 4://特价
                    break;
                case 5://全免配送费
                case 7://免部分配送费
                    freeDeliveryActivity = activity;
                    totalSubsidy = totalSubsidy.add(subsidy);
                    break;
                case 8://新用户活动
                case 9:
                    totalSubsidy = totalSubsidy.add(subsidy);
                    break;
                case 10://商家红包
                case 11://返红包
                    totalSubsidy = totalSubsidy.add(subsidy);
                    break;

            }


        }

        BigDecimal totalPay = order.getTotalpay();
        Integer drawMode = business.getDrawMode();
        boolean isDeliver = business.getIsDeliver() != null && business.getIsDeliver() == 1;
        if (isDeliver) {//自配送
            //商家所得
            orderUpdate.setBusinesspay(totalPay.add(totalSubsidy));

            BigDecimal businessDeliveryFee = order.getShowps();
            if (freeDeliveryActivity != null) {

                Double less = freeDeliveryActivity.getLess();
                Double subsidy = freeDeliveryActivity.getSubsidy();
                subsidy = subsidy == null ? 0d : subsidy;

                businessDeliveryFee = BigDecimal.valueOf(less).subtract(BigDecimal.valueOf(subsidy)); //商家所得配送费

            }


            //原价的总金额（包含配送费）
            orderUpdate.setDisprice(order.getPrice().add(order.getShowps()).add(order.getPacking()));


            if (drawMode == null || drawMode == 0) { //折后抽成
                baseFee = totalPay.subtract(businessDeliveryFee);//参与抽成的费用，自配送的配送费不参与抽成
            } else {
                //按照原价抽成
                baseFee = order.getPrice();//参与抽成的费用
            }


        } else {//非自配送

            //商家所得
            orderUpdate.setBusinesspay(totalPay.add(totalSubsidy).subtract(order.getShowps()));

            //原价的总金额（非自配送，商家显示是不包含配送费）
            orderUpdate.setDisprice(order.getPrice().add(order.getShowps()));


            if (drawMode == null || drawMode == 0) { //折后抽成
                baseFee = totalPay;//参与抽成的费用，自配送的配送费不参与抽成
            } else {
                //按照原价抽成
                baseFee = order.getPrice();//参与抽成的费用
            }

        }


        //总佣金
        BigDecimal totalIncome = BigDecimal.valueOf(0);

        if (parentAgent != null) {

            if (plateformCoefficient.compareTo(parentCoefficient) == 1) parentCoefficient = plateformCoefficient;
            if (parentCoefficient.compareTo(leafCoefficient) == 1) leafCoefficient = leafCoefficient;

            totalIncome = baseFee.multiply(leafCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);

            BigDecimal plateformIncome = baseFee.multiply(plateformCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            orderUpdate.setAgentget(plateformIncome);

            BigDecimal firstIncome = baseFee.multiply(parentCoefficient.subtract(plateformCoefficient)).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            orderUpdate.setAgentBusget2(firstIncome);

            BigDecimal secondIncome = baseFee.multiply(leafCoefficient.subtract(parentCoefficient)).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            orderUpdate.setAgentBusget(secondIncome.add(totalSubsidy)); //包含补贴


        } else {
            if (plateformCoefficient.compareTo(leafCoefficient) == 1) leafCoefficient = plateformCoefficient;

            totalIncome = baseFee.multiply(leafCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);

            BigDecimal plateformIncome = baseFee.multiply(plateformCoefficient).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            orderUpdate.setAgentget(plateformIncome);


            BigDecimal secondIncome = baseFee.multiply(leafCoefficient.subtract(plateformCoefficient)).divide(BigDecimal.valueOf(100), 6, RoundingMode.FLOOR);
            orderUpdate.setAgentBusget(secondIncome.add(totalSubsidy)); //包含补贴


        }

        orderUpdate.setBusinessget(totalIncome);


    }

    @Override
    public Result walletPay(Integer orderId, String password) {
        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);
        if (order == null) return Result.fail(ResultCode.FAIL, "该订单不存在");

        UserDataDetails<RunfastCuser> principal = (UserDataDetails<RunfastCuser>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        RunfastCuser cuser = principal.getData();

        if (!cuser.getPassword().equals(password)) return Result.fail(ResultCode.FAIL, "支付密码不正确");

        Integer status = order.getStatus();
        if (status != RunfastGoodsSellRecord.Status.created.getCode()) return Result.fail(ResultCode.FAIL, "新下的订单才能支付");
        BigDecimal totalpay = order.getTotalpay();
        BigDecimal remainder = cuser.getRemainder();
        remainder = remainder == null ? BigDecimal.valueOf(0) : remainder;

        BigDecimal totalremainder = cuser.getTotalremainder();
        if (totalremainder == null || totalremainder.compareTo(remainder) == -1) totalremainder = remainder;

        if (remainder.compareTo(totalpay) == -1) return Result.fail(ResultCode.FAIL, "用户可用余额不足");

        /**
         * 更新用户余额
         */
        RunfastCuser cuserUpdate = new RunfastCuser();
        cuserUpdate.setId(cuser.getId());
        cuserUpdate.setRemainder(remainder.subtract(totalpay));


        cuserUpdate.setTotalremainder(totalremainder.subtract(totalpay));

        cuserService.updateByPrimaryKeySelective(cuserUpdate);

        /**
         * 账户变动清单
         */
        RunfastAccountrecord ar = new RunfastAccountrecord();
        ar.setBeforemonety(cuser.getRemainder());

        ar.setBalance(remainder);
        ar.setCardnumber(order.getOrderCode());
        ar.setCid(cuser.getId());
        ar.setShowtype(1);
        ar.setMonetary(BigDecimal.ZERO.subtract(totalpay));
        ar.setCreateTime(new Date());
        ar.setType(0);
        ar.setTypename("消费");
        ar.setMobile(cuser.getMobile());
        ar.setName(cuser.getName());

        accountrecordService.insertSelective(ar);


        /**
         * 更新订单
         */
        RunfastGoodsSellRecord orderUpdated = new RunfastGoodsSellRecord();
        orderUpdated.setId(order.getId());
        orderUpdated.setStatus(RunfastGoodsSellRecord.Status.paid.getCode());
        orderUpdated.setStatStr("用户已付款");
        orderUpdated.setIsPay(1);
        orderUpdated.setPayTime(new Date());
        orderUpdated.setPayType(Channel.BALANCE.getCode());

        this.updateByPrimaryKeySelective(orderUpdated);

        /**
         * 保存订单状态
         */
        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();

        goodsSellOutStatus.setBusinessId(order.getBusinessId());
        goodsSellOutStatus.setBusinessName(order.getBusinessName());

        goodsSellOutStatus.setCreateTime(new Date());

        goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
        goodsSellOutStatus.setGoodsSellRecordId(order.getId());

        goodsSellOutStatus.setOperationId(order.getUserId());
        goodsSellOutStatus.setOperationName(order.getUserMobile());
        goodsSellOutStatus.setSort(RunfastGoodsSellRecord.Status.paid.getCode());
        goodsSellOutStatus.setStatStr("客户已付款 ");
        goodsSellOutStatus.setType(3);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

        statusService.insertSelective(goodsSellOutStatus);

        //用户下单通知
        messagePushTask.newOrderNotify(this.selectByPrimaryKey(orderId));


        return Result.ok("");
    }


    @Override
    public Result businessTake(RunfastGoodsSellRecord order) {

        /**
         * 更新订单
         */
        RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
        orderUpdate.setId(order.getId());
        orderUpdate.setStatus(Status.business_taken.getCode());
        orderUpdate.setStatStr("商家接单");
        orderUpdate.setAceptTime(new Date());

        /*Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, order.getDistributionTime());
        orderUpdate.setDisTime(now.getTime());*/

        this.updateByPrimaryKeySelective(orderUpdate);


        /*订单状态操作记录*/
        RunfastGoodsSellOutStatus goodsSellOutStatus = new RunfastGoodsSellOutStatus();
        Integer businessId = order.getBusinessId();
        goodsSellOutStatus.setBusinessId(businessId);
        goodsSellOutStatus.setBusinessName(order.getBusinessName());
        goodsSellOutStatus.setCreateTime(new Date());
        goodsSellOutStatus.setGoodsSellRecordCode(order.getOrderCode());
        goodsSellOutStatus.setGoodsSellRecordId(order.getId());
        goodsSellOutStatus.setOperationId(-1);
        goodsSellOutStatus.setOperationName("系统");
        goodsSellOutStatus.setSort(2);
        goodsSellOutStatus.setStatStr("商家接单");
        goodsSellOutStatus.setType(1);//操作人类型 0：后台管理员，1：商家  ，2:快递员  ，3：用户

        goodsSellOutStatusService.insertSelective(goodsSellOutStatus);


        /**
         * 订单通知
         */

        messagePushTask.takenOrderNotity(order);


        /**
         * wifi打印
         */
        RunfastBusiness business = businessService.selectByPrimaryKey(businessId);
        Result printResult = printerService.print(order, business);

        log.info("wifi打印信息：" + printResult.toString());


        return Result.ok("");
    }


    @Override
    public Result complete(Integer orderId) {

        RunfastGoodsSellRecord order = this.selectByPrimaryKey(orderId);
        if (order == null) return Result.fail(ResultCode.FAIL, "订单不存在");

        Integer status = order.getStatus();
        if (status != 5) return Result.fail(ResultCode.FAIL, "配送中的订单才能手动完成");

        Integer userId = order.getUserId();
        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);

        /**
         * 更新订单状态
         */
        RunfastGoodsSellRecord orderUpdate = new RunfastGoodsSellRecord();
        orderUpdate.setId(orderId);
        orderUpdate.setStatus(Status.completed.getCode());
        orderUpdate.setStatStr("订单完成");
        orderUpdate.setReadyTime(new Date());
        this.updateByPrimaryKeySelective(orderUpdate);

        return autoComplete(cuser, order);
    }


}